// 封装获取元素
const qs = ele => document.querySelector(ele)

// 接口地址：https://www.apifox.cn/apidoc/shared-36f0cbc0-9064-44bc-850a-805e263bf494/api-25827426
// 需求
// 1、默认是安徽省合肥市瑶海区
// 2、点击省联动市的数据，点击市的数据联动区的数据
// 请求根目录
axios.defaults.baseURL = 'http://124.223.14.236:3001/api'

// 1、默认安徽省合肥市瑶海区
async function init() {
    // 安徽省
    const { data } = await axios.get('/city/province')
    const provinceStr = data.data.map(item => `<option value="${item.province}">${item.name}</option>`).join('')
    qs('#province').innerHTML = `<option value="">请选择省份</option>` + provinceStr
    qs('#province').value = 34


    // 合肥市
    const { data: { data: cityData } } = await axios.get('/city/city', {
        params: {
            provinceCode: '34'
        }
    })
    const cityStr = cityData.map(item => `<option value="${item.city}">${item.name}</option>`).join('')
    qs('#city').innerHTML = `<option value="">请选择城市</option>` + cityStr
    qs('#city').value = '01'


    // 瑶海区
    const { data: { data: areaData } } = await axios.get('/city/area', {
        params: {
            provinceCode: '34',
            cityCode: '01'
        }
    })
    const areaStr = areaData.map(item => `<option value="${item.area}">${item.name}</option>`).join('')
    qs('#county').innerHTML = `<option value="">请选择区县</option>` + areaStr
    qs('#county').value = '02'
}
init()


// 2、省市区联动

qs('#province').addEventListener('change', async function () {
    const { data: { data: cityData } } = await axios.get('/city/city', {
        params: {
            provinceCode: this.value
        }
    })
    const cityStr = cityData.map(item => `<option value="${item.city}">${item.name}</option>`).join('')
    qs('#city').innerHTML = `<option value="">请选择城市</option>` + cityStr
    // 
    qs('#county').innerHTML = `<option value="">请选择区县</option>`
})

qs('#city').addEventListener('change', async function () {
    const { data: { data: areaData } } = await axios.get('/city/area', {
        params: {
            provinceCode: qs('#province').value,
            cityCode: this.value
        }
    })
    const areaStr = areaData.map(item => `<option value="${item.area}">${item.name}</option>`).join('')
    qs('#county').innerHTML = `<option value="">请选择区县</option>` + areaStr
})

